<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> 
    <title> - 天地维杰网</title>
    <meta name="keywords" content="系统架构,shutdown,不与天斗,Domino,博客,程序员,架构师,笔记,技术,分享,java,Redis">
    
    <meta property="og:title" content="">
    <meta property="og:site_name" content="天地维杰网">
    <meta property="og:image" content="/img/author.jpg"> 
    <meta name="title" content=" - 天地维杰网" />
    <meta name="description" content="天地维杰网 | 博客 | 软件 | 架构 | Java "> 
    <link rel="shortcut icon" href="http://www.shutdown.cn/img/favicon.ico" />
    <link rel="apple-touch-icon" href="http://www.shutdown.cn/img/apple-touch-icon.png" />
    <link rel="apple-touch-icon-precomposed" href="http://www.shutdown.cn/img/apple-touch-icon.png" />
    <link href="http://www.shutdown.cn/js/vendor/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/js/vendor/fancybox/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/css/main.css" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/css/syntax.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
     fancybox: true, 
    motion: true
  };
</script>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<div class="container one-collumn sidebar-position-left page-home  ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-meta  custom-logo ">

  <div class="custom-logo-site-title">
    <a href="http://www.shutdown.cn"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">天地维杰网</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">人如秋鸿来有信，事若春梦了无痕</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
    <ul id="menu" class="menu">
      
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/redis/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-battery-full"></i> <br />Redis
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/java/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-coffee"></i> <br />java
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/linux/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-linux"></i> <br />linux
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/daily/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-bug"></i> <br />日常问题
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/spring/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-child"></i> <br />Spring和Springboot
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/spring/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-fire"></i> <br />Mac相关
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/middleware/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-gavel"></i> <br />中间件
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/jiagou/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-rocket"></i> <br />架构
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/python/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-ship"></i> <br />python
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/front/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-bolt"></i> <br />前端
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/jvm/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-balance-scale"></i> <br />JVM
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/post/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/about/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于
          </a>
        </li>
      
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger"> <i class="menu-item-icon fa fa-search fa-fw"></i> <br /> 搜索</a>
      </li>
    </ul>
    <div class="site-search">
      <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>

    </div>
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            
<section id="posts" class="posts-expand">
  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <header class="post-header">
      <h1 class="post-title" itemprop="name headline">
        <a class="post-title-link" href="http://www.shutdown.cn/post/jedispool%E8%B5%84%E6%BA%90%E6%B1%A0%E4%BC%98%E5%8C%96/" itemprop="url">
        
        </a>
      </h1>
      <div class="post-meta">
      <span class="post-time">
<span class="post-meta-item-icon">
    <i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">时间：</span>
<time itemprop="dateCreated" datetime="2016-03-22T13:04:35+08:00" content="0001-01-01">
    0001-01-01
</time>
</span> 
      
      
       <span>
&nbsp; | &nbsp;
<span class="post-meta-item-icon">
    <i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读：</span>
<span class="leancloud-visitors-count">311 字 ~2分钟</span>
</span>
      </div>
    </header>
    <div class="post-body" itemprop="articleBody">
    

    

<h1 id="jedispool资源池优化">JedisPool资源池优化</h1>

<p>合理的JedisPool资源池参数设置能够有效地提升Redis性能。本文档将对JedisPool的使用和资源池的参数进行详细说明，并提供优化配置的建议。</p>

<h2 id="使用方法">使用方法</h2>

<p>以Jedis 2.9.0为例，其Maven依赖如下：</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-xml" data-lang="xml"><span style="color:#204a87;font-weight:bold">&lt;dependency</span><span style="color:#204a87;font-weight:bold">&gt;</span>
    <span style="color:#204a87;font-weight:bold">&lt;groupId</span><span style="color:#204a87;font-weight:bold">&gt;</span>redis.clients<span style="color:#204a87;font-weight:bold">&lt;/groupId&gt;</span>
    <span style="color:#204a87;font-weight:bold">&lt;artifactId</span><span style="color:#204a87;font-weight:bold">&gt;</span>jedis<span style="color:#204a87;font-weight:bold">&lt;/artifactId&gt;</span>
    <span style="color:#204a87;font-weight:bold">&lt;version</span><span style="color:#204a87;font-weight:bold">&gt;</span>2.9.0<span style="color:#204a87;font-weight:bold">&lt;/version&gt;</span>
    <span style="color:#204a87;font-weight:bold">&lt;scope</span><span style="color:#204a87;font-weight:bold">&gt;</span>compile<span style="color:#204a87;font-weight:bold">&lt;/scope&gt;</span>
<span style="color:#204a87;font-weight:bold">&lt;/dependency&gt;</span></code></pre></div>
<p>Jedis使用Apache Commons-pool2对资源池进行管理，在定义JedisPool时需注意其关键参数<strong>GenericObjectPoolConfig</strong>（资源池）。该参数的使用示例如下，其中的参数的说明请参见下文。</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java" data-lang="java"><span style="color:#000">GenericObjectPoolConfig</span> <span style="color:#000">jedisPoolConfig</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#204a87;font-weight:bold">new</span> <span style="color:#000">GenericObjectPoolConfig</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
<span style="color:#000">jedisPoolConfig</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">setMaxTotal</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
<span style="color:#000">jedisPoolConfig</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">setMaxIdle</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
<span style="color:#000">jedisPoolConfig</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">setMinIdle</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
<span style="color:#000">jedisPoolConfig</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">setMaxWaitMillis</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
<span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#ce5c00;font-weight:bold">.</span></code></pre></div>
<p>JedisPool的初始化方法如下：</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java" data-lang="java"><span style="color:#8f5902;font-style:italic">// redisHost为实例的IP， redisPort 为实例端口，redisPassword 为实例的密码，timeout 既是连接超时又是读写超时
</span><span style="color:#8f5902;font-style:italic"></span><span style="color:#000">JedisPool</span> <span style="color:#000">jedisPool</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#204a87;font-weight:bold">new</span> <span style="color:#000">JedisPool</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#000">jedisPoolConfig</span><span style="color:#ce5c00;font-weight:bold">,</span> <span style="color:#000">redisHost</span><span style="color:#ce5c00;font-weight:bold">,</span> <span style="color:#000">redisPort</span><span style="color:#ce5c00;font-weight:bold">,</span> <span style="color:#000">timeout</span><span style="color:#ce5c00;font-weight:bold">,</span> <span style="color:#000">redisPassword</span><span style="color:#8f5902;font-style:italic">//);
</span><span style="color:#8f5902;font-style:italic"></span><span style="color:#8f5902;font-style:italic">//执命令如下
</span><span style="color:#8f5902;font-style:italic"></span><span style="color:#000">Jedis</span> <span style="color:#000">jedis</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#204a87;font-weight:bold">null</span><span style="color:#ce5c00;font-weight:bold">;</span>
<span style="color:#204a87;font-weight:bold">try</span> <span style="color:#ce5c00;font-weight:bold">{</span>
    <span style="color:#000">jedis</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#000">jedisPool</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">getResource</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
    <span style="color:#8f5902;font-style:italic">//具体的命令
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#000">jedis</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">executeCommand</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">)</span>
<span style="color:#ce5c00;font-weight:bold">}</span> <span style="color:#204a87;font-weight:bold">catch</span> <span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#000">Exception</span> <span style="color:#000">e</span><span style="color:#ce5c00;font-weight:bold">)</span> <span style="color:#ce5c00;font-weight:bold">{</span>
    <span style="color:#000">logger</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">error</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#000">e</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">getMessage</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">,</span> <span style="color:#000">e</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
<span style="color:#ce5c00;font-weight:bold">}</span> <span style="color:#204a87;font-weight:bold">finally</span> <span style="color:#ce5c00;font-weight:bold">{</span>
    <span style="color:#8f5902;font-style:italic">//在 JedisPool 模式下，Jedis 会被归还给资源池
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#204a87;font-weight:bold">if</span> <span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#000">jedis</span> <span style="color:#ce5c00;font-weight:bold">!</span><span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#204a87;font-weight:bold">null</span><span style="color:#ce5c00;font-weight:bold">)</span> 
        <span style="color:#000">jedis</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">close</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
<span style="color:#ce5c00;font-weight:bold">}</span></code></pre></div>
<h2 id="参数说明">参数说明</h2>

<p>Jedis连接就是连接池中JedisPool管理的资源，JedisPool保证资源在一个可控范围内，并且保障线程安全。使用合理的<strong>GenericObjectPoolConfig</strong>配置能够提升Redis的服务性能，降低资源开销。下列两表将对一些重要参数进行说明，并提供设置建议。</p>

<table>
<thead>
<tr>
<th align="left">参数</th>
<th align="left">说明</th>
<th align="left">默认值</th>
<th align="left">建议</th>
</tr>
</thead>

<tbody>
<tr>
<td align="left">maxTotal</td>
<td align="left">资源池中的最大连接数</td>
<td align="left">8</td>
<td align="left">参见<a href="https://www.alibabacloud.com/#section-m2c-5kr-zfb">关键参数设置建议</a>。</td>
</tr>

<tr>
<td align="left">maxIdle</td>
<td align="left">资源池允许的最大空闲连接数</td>
<td align="left">8</td>
<td align="left">参见<a href="https://www.alibabacloud.com/#section-m2c-5kr-zfb">关键参数设置建议</a>。</td>
</tr>

<tr>
<td align="left">minIdle</td>
<td align="left">资源池确保的最少空闲连接数</td>
<td align="left">0</td>
<td align="left">参见<a href="https://www.alibabacloud.com/#section-m2c-5kr-zfb">关键参数设置建议</a>。</td>
</tr>

<tr>
<td align="left">blockWhenExhausted</td>
<td align="left">当资源池用尽后，调用者是否要等待。只有当值为true时，下面的<strong>maxWaitMillis</strong>才会生效。</td>
<td align="left">true</td>
<td align="left">建议使用默认值。</td>
</tr>

<tr>
<td align="left">maxWaitMillis</td>
<td align="left">当资源池连接用尽后，调用者的最大等待时间（单位为毫秒）。</td>
<td align="left">-1（表示永不超时）</td>
<td align="left">不建议使用默认值。</td>
</tr>

<tr>
<td align="left">testOnBorrow</td>
<td align="left">向资源池借用连接时是否做连接有效性检测（ping）。检测到的无效连接将会被移除。</td>
<td align="left">false</td>
<td align="left">业务量很大时候建议设置为false，减少一次ping的开销。</td>
</tr>

<tr>
<td align="left">testOnReturn</td>
<td align="left">向资源池归还连接时是否做连接有效性检测（ping）。检测到无效连接将会被移除。</td>
<td align="left">false</td>
<td align="left">业务量很大时候建议设置为false，减少一次ping的开销。</td>
</tr>

<tr>
<td align="left">jmxEnabled</td>
<td align="left">是否开启JMX监控</td>
<td align="left">true</td>
<td align="left">建议开启，请注意应用本身也需要开启。</td>
</tr>
</tbody>
</table>

<p>空闲Jedis对象检测由下列四个参数组合完成。</p>

<table>
<thead>
<tr>
<th align="left">名称</th>
<th align="left">说明</th>
<th align="left">默认值</th>
<th align="left">建议</th>
</tr>
</thead>

<tbody>
<tr>
<td align="left">testWhileIdle</td>
<td align="left">是否在空闲资源监测时通过ping命令监测连接有效性，无效连接将被销毁。</td>
<td align="left">false</td>
<td align="left">true</td>
</tr>

<tr>
<td align="left">timeBetweenEvictionRunsMillis</td>
<td align="left">空闲资源的检测周期（单位为毫秒）</td>
<td align="left">-1（不检测）</td>
<td align="left">建议设置，周期自行选择，也可以默认也可以使用下方<strong>JedisPoolConfig</strong> 中的配置。</td>
</tr>

<tr>
<td align="left">minEvictableIdleTimeMillis</td>
<td align="left">资源池中资源的最小空闲时间（单位为毫秒），达到此值后空闲资源将被移除。</td>
<td align="left">1,800,000（即30分钟）</td>
<td align="left">可根据自身业务决定，一般默认值即可，也可以考虑使用下方<strong>JeidsPoolConfig</strong>中的配置。</td>
</tr>

<tr>
<td align="left">numTestsPerEvictionRun</td>
<td align="left">做空闲资源检测时，每次检测资源的个数。</td>
<td align="left">3</td>
<td align="left">可根据自身应用连接数进行微调，如果设置为 -1，就是对所有连接做空闲监测。</td>
</tr>
</tbody>
</table>

<p>为了方便使用，Jedis提供了<strong>JedisPoolConfig</strong>，它继承了<strong>GenericObjectPoolConfig</strong>在空闲检测上的一些设置。</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java" data-lang="java"><span style="color:#204a87;font-weight:bold">public</span> <span style="color:#204a87;font-weight:bold">class</span> <span style="color:#000">JedisPoolConfig</span> <span style="color:#204a87;font-weight:bold">extends</span> <span style="color:#000">GenericObjectPoolConfig</span> <span style="color:#ce5c00;font-weight:bold">{</span>
  <span style="color:#204a87;font-weight:bold">public</span> <span style="color:#000">JedisPoolConfig</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">)</span> <span style="color:#ce5c00;font-weight:bold">{</span>
    <span style="color:#8f5902;font-style:italic">// defaults to make your life with connection pool easier :)
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#000">setTestWhileIdle</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#204a87;font-weight:bold">true</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
    <span style="color:#8f5902;font-style:italic">//
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#000">setMinEvictableIdleTimeMillis</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#000">60000</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
    <span style="color:#8f5902;font-style:italic">//
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#000">setTimeBetweenEvictionRunsMillis</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#000">30000</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
    <span style="color:#000">setNumTestsPerEvictionRun</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">-</span><span style="color:#000">1</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
    <span style="color:#ce5c00;font-weight:bold">}</span>
<span style="color:#ce5c00;font-weight:bold">}</span></code></pre></div>
<p><strong>说明</strong> 可以在<strong>org.apache.commons.pool2.impl.BaseObjectPoolConfig</strong>中查看全部默认值。</p>

<h2 id="关键参数设置建议">关键参数设置建议</h2>

<p><strong>maxTotal</strong>（最大连接数）</p>

<p>想合理设置<strong>maxTotal</strong>（最大连接数）需要考虑的因素较多，如：</p>

<ul>
<li>业务希望的Redis并发量；</li>
<li>客户端执行命令时间；</li>
<li>Redis资源，例如nodes （如应用ECS个数等） * maxTotal不能超过Redis的最大连接数（可在实例详情页面查看）；</li>
<li>资源开销，例如虽然希望控制空闲连接，但又不希望因为连接池中频繁地释放和创建连接造成不必要的开销。</li>
</ul>

<p>假设一次命令时间，即borrow|return resource加上Jedis执行命令 （ 含网络耗时）的平均耗时约为1ms，一个连接的QPS大约是1s/1ms = 1000，而业务期望的单个Redis的QPS是50000（业务总的QPS/Redis分片个数），那么理论上需要的资源池大小（即MaxTotal）是50000 / 1000 = 50。</p>

<p>但事实上这只是个理论值，除此之外还要预留一些资源，所以<strong>maxTotal</strong>可以比理论值大一些。这个值不是越大越好，一方面连接太多会占用客户端和服务端资源，另一方面对于Redis这种高QPS的服务器，如果出现大命令的阻塞，即使设置再大的资源池也无济于事。</p>

<p><strong>maxIdle与minIdle</strong></p>

<p><strong>maxIdle</strong>实际上才是业务需要的最大连接数，<strong>maxTotal</strong> 是为了给出余量，所以 <strong>maxIdle</strong> 不要设置得过小，否则会有<code>new Jedis</code>（新连接）开销，而<strong>minIdle</strong>是为了控制空闲资源检测。</p>

<p>连接池的最佳性能是<strong>maxTotal</strong>=<strong>maxIdle</strong>，这样就避免了连接池伸缩带来的性能干扰。如果您的业务存在突峰访问，建议设置这两个参数的值相等；如果并发量不大或者<strong>maxIdle</strong>设置过高，则会导致不必要的连接资源浪费。</p>

<p>您可以根据实际总QPS和调用Redis的客户端规模整体评估每个节点所使用的连接池大小。</p>

<p><strong>使用监控获取合理值</strong></p>

<p>在实际环境中，比较可靠的方法是通过监控来尝试获取参数的最佳值。可以考虑通过JMX等方式实现监控，从而找到合理值。</p>

<h2 id="常见问题">常见问题</h2>

<p><strong>资源不足</strong></p>

<p>下面两种情况均属于无法从资源池获取到资源。</p>

<ul>
<li><p>超时：</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-fallback" data-lang="fallback">redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
…
Caused by: java.util.NoSuchElementException: Timeout waiting for idle object
at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:449)</code></pre></div></li>

<li><p><strong>blockWhenExhausted</strong> 为false，因此不会等待资源释放：</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-fallback" data-lang="fallback">redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
…
Caused by: java.util.NoSuchElementException: Pool exhausted
at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:464)</code></pre></div></li>
</ul>

<p>此类异常的原因不一定是资源池不够大，请参见<strong><a href="https://www.alibabacloud.com/#section-m2c-5kr-zfb">关键参数设置建议</a></strong>中的分析。建议从网络、资源池参数设置、资源池监控（如果对JMX监控）、代码（例如没执行<code>jedis.close()</code>）、慢查询、DNS等方面进行排查。</p>

<p><strong>预热JedisPool</strong></p>

<p>由于一些原因（如超时时间设置较小等），项目在启动成功后可能会出现超时。JedisPool定义最大资源数、最小空闲资源数时，不会在连接池中创建Jedis连接。初次使用时，池中没有资源使用则会先<code>new Jedis</code>，使用后再放入资源池，该过程会有一定的时间开销，所以建议在定义JedisPool后，以最小空闲数量为基准对JedisPool进行预热，示例如下：</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java" data-lang="java"><span style="color:#000">List</span><span style="color:#ce5c00;font-weight:bold">&lt;</span><span style="color:#000">Jedis</span><span style="color:#ce5c00;font-weight:bold">&gt;</span> <span style="color:#000">minIdleJedisList</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#204a87;font-weight:bold">new</span> <span style="color:#000">ArrayList</span><span style="color:#ce5c00;font-weight:bold">&lt;</span><span style="color:#000">Jedis</span><span style="color:#ce5c00;font-weight:bold">&gt;</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#000">jedisPoolConfig</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">getMinIdle</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>

<span style="color:#204a87;font-weight:bold">for</span> <span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#204a87;font-weight:bold">int</span> <span style="color:#000">i</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#000">0</span><span style="color:#ce5c00;font-weight:bold">;</span> <span style="color:#000">i</span> <span style="color:#ce5c00;font-weight:bold">&lt;</span> <span style="color:#000">jedisPoolConfig</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">getMinIdle</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span> <span style="color:#000">i</span><span style="color:#ce5c00;font-weight:bold">+</span><span style="color:#ce5c00;font-weight:bold">+</span><span style="color:#ce5c00;font-weight:bold">)</span> <span style="color:#ce5c00;font-weight:bold">{</span>
    <span style="color:#000">Jedis</span> <span style="color:#000">jedis</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#204a87;font-weight:bold">null</span><span style="color:#ce5c00;font-weight:bold">;</span>
    <span style="color:#204a87;font-weight:bold">try</span> <span style="color:#ce5c00;font-weight:bold">{</span>
        <span style="color:#000">jedis</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#000">pool</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">getResource</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
        <span style="color:#000">minIdleJedisList</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">add</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#000">jedis</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
        <span style="color:#000">jedis</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">ping</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
    <span style="color:#ce5c00;font-weight:bold">}</span> <span style="color:#204a87;font-weight:bold">catch</span> <span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#000">Exception</span> <span style="color:#000">e</span><span style="color:#ce5c00;font-weight:bold">)</span> <span style="color:#ce5c00;font-weight:bold">{</span>
        <span style="color:#000">logger</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">error</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#000">e</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">getMessage</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">,</span> <span style="color:#000">e</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
    <span style="color:#ce5c00;font-weight:bold">}</span> <span style="color:#204a87;font-weight:bold">finally</span> <span style="color:#ce5c00;font-weight:bold">{</span>
    <span style="color:#ce5c00;font-weight:bold">}</span>
<span style="color:#ce5c00;font-weight:bold">}</span>

<span style="color:#204a87;font-weight:bold">for</span> <span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#204a87;font-weight:bold">int</span> <span style="color:#000">i</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#000">0</span><span style="color:#ce5c00;font-weight:bold">;</span> <span style="color:#000">i</span> <span style="color:#ce5c00;font-weight:bold">&lt;</span> <span style="color:#000">jedisPoolConfig</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">getMinIdle</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span> <span style="color:#000">i</span><span style="color:#ce5c00;font-weight:bold">+</span><span style="color:#ce5c00;font-weight:bold">+</span><span style="color:#ce5c00;font-weight:bold">)</span> <span style="color:#ce5c00;font-weight:bold">{</span>
    <span style="color:#000">Jedis</span> <span style="color:#000">jedis</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#204a87;font-weight:bold">null</span><span style="color:#ce5c00;font-weight:bold">;</span>
    <span style="color:#204a87;font-weight:bold">try</span> <span style="color:#ce5c00;font-weight:bold">{</span>
        <span style="color:#000">jedis</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#000">minIdleJedisList</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">get</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#000">i</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
        <span style="color:#000">jedis</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">close</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
    <span style="color:#ce5c00;font-weight:bold">}</span> <span style="color:#204a87;font-weight:bold">catch</span> <span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#000">Exception</span> <span style="color:#000">e</span><span style="color:#ce5c00;font-weight:bold">)</span> <span style="color:#ce5c00;font-weight:bold">{</span>
        <span style="color:#000">logger</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">error</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#000">e</span><span style="color:#ce5c00;font-weight:bold">.</span><span style="color:#c4a000">getMessage</span><span style="color:#ce5c00;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">,</span> <span style="color:#000">e</span><span style="color:#ce5c00;font-weight:bold">)</span><span style="color:#ce5c00;font-weight:bold">;</span>
    <span style="color:#ce5c00;font-weight:bold">}</span> <span style="color:#204a87;font-weight:bold">finally</span> <span style="color:#ce5c00;font-weight:bold">{</span>
    
    <span style="color:#ce5c00;font-weight:bold">}</span>
<span style="color:#ce5c00;font-weight:bold">}</span></code></pre></div>
    </div>
    <footer class="post-footer">
     

     <div class="post-nav">
    <div class="post-nav-next post-nav-item">
    
        <a href="http://www.shutdown.cn/post/java%E5%A4%9A%E7%BA%BF%E7%A8%8B%E7%BC%96%E7%A8%8B%E6%A0%B8%E5%BF%83%E6%8A%80%E6%9C%AF01-java%E5%A4%9A%E7%BA%BF%E7%A8%8B%E6%8A%80%E8%83%BD/" rel="next" title="">
        <i class="fa fa-chevron-left"></i> 
        </a>
    
    </div>

    <div class="post-nav-prev post-nav-item">
    
        <a href="http://www.shutdown.cn/post/jmeter%E8%BF%9B%E8%A1%8C%E5%8E%8B%E5%8A%9B%E6%B5%8B%E8%AF%95/" rel="prev" title="">
         <i class="fa fa-chevron-right"></i>
        </a>
    
    </div>
</div>
      
     
     
     






    </footer>
  </article>
</section>

          </div>
        </div>
        <div class="sidebar-toggle">
  <div class="sidebar-toggle-line-wrap">
    <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
    <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
    <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
  </div>
</div>
<aside id="sidebar" class="sidebar">
  <div class="sidebar-inner">

    <section class="site-overview sidebar-panel  sidebar-panel-active ">
      <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
        src="http://www.shutdown.cn/img/author.jpg"
        alt="不与天斗Domino" />
    <p class="site-author-name" itemprop="name">不与天斗Domino</p>
    <p class="site-description motion-element" itemprop="description"> 
        Programmer &amp; Architect</p>
</div>
      <nav class="site-state motion-element">
    <div class="site-state-item site-state-posts">
      <a href="http://www.shutdown.cn/post/">
        <span class="site-state-item-count">172</span>
        <span class="site-state-item-name">日志</span>
      </a>
    </div>
    <div class="site-state-item site-state-categories">    
        <a href="http://www.shutdown.cn/categories/">      
         
        <span class="site-state-item-count">10</span>
        
        <span class="site-state-item-name">分类</span>
        
        </a>
    </div>

    <div class="site-state-item site-state-tags">
        <a href="http://www.shutdown.cn/tags/">
         
        <span class="site-state-item-count">96</span>
        
        <span class="site-state-item-name">标签</span>
        </a>
    </div>
</nav>
      
      

      

      <div class="links-of-blogroll motion-element inline">
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=&amp;m=0&amp;s=220&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33&amp;bv=35" async="async"></script>
</div>

    </section>
    
  </div>
</aside>

      </div>
    </main>
   
    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  <span itemprop="copyrightYear">  &copy; 
  2013 - 2022</span>
  <span class="with-love"><i class="fa fa-heart"></i></span>
  <span class="author" itemprop="copyrightHolder">天地维杰网</span>
  <span class="icp" itemprop="copyrightHolder"><a href="https://beian.miit.gov.cn/" target="_blank">京ICP备13019191号-1</a></span>
</div>
<div class="powered-by">
  Powered by - <a class="theme-link" href="http://gohugo.io" target="_blank" title="hugo" >Hugo v0.63.2</a>
</div>
<div class="theme-info">
  Theme by - <a class="theme-link" href="https://github.com/xtfly/hugo-theme-next" target="_blank"> NexT
  </a>
</div>


      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
      <span id="scrollpercent"><span>0</span>%</span>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/fastclick/lib/fastclick.min.js?v=1.0.6"></script> 
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/velocity/velocity.min.js?v=1.2.1"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="http://www.shutdown.cn/js/vendor/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>

<script src="http://www.shutdown.cn/js/vendor/fancybox/jquery.fancybox.pack.js?v=2.1.5"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/utils.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/motion.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/affix.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/schemes/pisces.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/scrollspy.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/post-details.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/toc.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/bootstrap.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js"],
    jax: ["input/TeX", "output/HTML-CSS"],
    tex2jax: {
      inlineMath: [ ['$','$'] ],
      displayMath: [ ['$$','$$'] ],
      processEscapes: true
    },
    "HTML-CSS": { fonts: ["TeX"] }
  });
</script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML' async></script>
</body>
</html>